<template>
  <div class="alloc-menu">
    <el-tree
      :data="menuNodeList"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      highlight-current
      :default-checked-keys="checkedKeys"
      :props="defaultProps">
    </el-tree>
    <div class="btns-line">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="resetChecked">清空</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getMenuNodeList, getRoleMenu, allocateRoleMenus } from '@/services/menu'
import { Tree } from 'element-ui'

export default Vue.extend({
  name: 'AllocMenu',

  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },

  data () {
    return {
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      menuNodeList: [],
      checkedKeys: []
    }
  },

  mounted () {
    this.loadMenuNodeList()
    this.loadRoleMenu()
  },

  methods: {
    loadMenuNodeList () {
      getMenuNodeList().then(res => {
        if (res.data.code === '000000') {
          this.menuNodeList = res.data.data
        }
      })
    },

    loadRoleMenu () {
      getRoleMenu(this.roleId).then(res => {
        if (res.data.code === '000000') {
          const list = res.data.data
          const tmp: [] = []
          this.getKeys(list, tmp)
          this.checkedKeys = tmp
        }
      })
    },

    getKeys (list: any[], ret: any[]) {
      list.forEach(item => {
        if (!item.selected) return
        ret.push(item.id)
        if (item.subMenuList) {
          this.getKeys(item.subMenuList, ret)
        }
      })
    },

    resetChecked () {
      (this.$refs.tree as Tree).setCheckedKeys([])
    },

    save () {
      const menuIdList = (this.$refs.tree as Tree).getCheckedKeys()
      allocateRoleMenus({
        roleId: this.roleId,
        menuIdList
      }).then(res => {
        if (res.data.code === '000000') {
          this.$message.success('操作成功')
          this.$router.back()
        }
      })
    }
  }
})
</script>

<style lang="scss" scoped>
.alloc-menu{
    background: #fff;
    padding: 20px;
}
.btns-line{
    margin-top: 20px;
    text-align: center;
}
</style>
